package com.filter;

import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.annotation.WebInitParam;

import java.io.IOException;
import java.util.Objects;

//相同路径/* 下按照字母顺序执行Filter链 所以是CharacterEncodingFilter 》 Filter1 》 Filter2
@WebFilter(value = "/*",initParams = {@WebInitParam(name = "encoding",value = "UTF-8")})
public class CharacterEncodingFilter implements Filter {
    private String encoding = "UTF-8";
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        servletResponse.setContentType("text/html");
        servletRequest.setCharacterEncoding("UTF-8");
        servletResponse.setCharacterEncoding("UTF-8");
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        String encdingParam = filterConfig.getInitParameter("encoding");
        if(Objects.nonNull(encdingParam) && ! encdingParam.isEmpty()){
            encoding = encdingParam;
        }
    }
}

